<template>
  <div class="report">
    <van-nav-bar
      title="智能核保助手"
      left-text="返回"
      fixed
      placeholder
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="header-timer">{{ taskNo }}</div>
    <div class="header">
      亲，感谢您提交体检报告，小智马上为您进行分析，请稍作等待哦。
    </div>
    <div class="qr-scanner">
      <div class="box">
        <div class="line" v-if="![1, 2, 3].includes(respFlag)"></div>
        <div class="angle"></div>
        <img :src="imgSrc" class="img" />
      </div>
    </div>
    <div class="footer">
      <div class="footer-item">
        <img src="../assets/img/jqr.png" class="robot-icon" />
        <div class="footer-text">
          <p v-for="(value, key) in displayTextObj" :class="key" :key="key">
            {{ value }}
          </p>
          <div v-if="respFlag === 4">
            <p class="p6">症状程度分析完成。</p>
            <p class="p6">正在评估您的核保预测结果……</p>
          </div>
          <p class="p6" style="color: red;" v-if="respFlag === 1">网络不稳定，请重试。</p>
          <p class="p6" style="color: red;" v-else-if="respFlag === 2">
            {{ errorMsg }}
          </p>
        </div>
      </div>
    </div>
    <van-button
      type="danger"
      class="footer-btn"
      v-if="[1, 2].includes(respFlag)"
      @click="submit(respFlag)"
      >{{ respFlag == 1 ? "重新提交" : "重新评估" }}</van-button
    >
  </div>
</template>

<script>
import dayjs from "dayjs";
import { PlanResultApi,recognizeApi,identifyingApi } from "@/api/requestApi";
export default {
  name: "report",
  components: {},
  data() {
    return {
      timeoutId:{},
      intervalId1:{},
      intervalId2:{},
      taskNo:"",
      imgSrc: "",
      timer: dayjs().format("YYYYMMDD"),
      clearTimer: null,
      getPlanResult: null,
      textObj: {
        title:
          "根据您提供的体检报告，小智正在为您分析核保预测结果，整个分析的过程大概需要1分钟。",
        p1: "正在提取图片里的内容……",
        p2: "文字内容提取完成。",
        p3: "正在分析体检报告内容……",
        p4: "体检报告内容分析完成。",
        p5: "正在评估您的核保预测结果……",
      },
      flagObj: {
        success: "症状分析完成。",
        fail: "您提供的图片里不存在体检项目信息，无法进行评估，请重新拍照上传。",
        notNetwork: "网络通信不稳定，请重试",
      },
      displayTextObj: {
        title: "",
        p1: "",
        p2: "",
        p3: "",
        p4: "",
        p5: "",
      },
      respFlag: 0, // 最终响应标识
      respFlag1: 0, // 响应标识中转站
      respFlag2: 0, // 是否停止遍历文字
      errorMsg:'',
    };
  },

  created(){},
  async mounted() {
    this.$nextTick(()=>{
      let orcParam = JSON.parse(sessionStorage.getItem("orcParam"))
      if (orcParam) {
        this.params = orcParam;
      }
      // this.imgSrc = 'data:image/jpg;base64,'+ this.params.Base64Img;
			this.imgSrc = this.params.Base64Img;
      this.taskNo = sessionStorage.getItem('taskNo');
      console.log('this.taskNo',this.taskNo);
    })
    this.clearTimer = setInterval(() => {
      this.nowDate();
    }, 1000);
    this.getPlanResult = setInterval(() => {
      this.getPlanResultFn();
    }, 2000);
    // 网络请求
    // this.gptRequest();
    // 遍历文字
    await this.traversalText();
    // this.getrespFlag();
  },
  beforeDestroy() {
    // 清除定时器
    clearInterval(this.clearTimer);
    clearInterval(this.getPlanResult);
  },
  methods: {
    onClickLeft() {
      this.$router.go(-1);
    },
    //重新提交或重新评估
    async submit(val) {
      //重新提交
      if (val == 1) {
        this.reSubmitOcr();
        this.displayTextObj = { title: "",p1: "", p2: "",p3: "",p4: "",p5: ""}
        this.clearOcrTextInterval();
        await this.traversalText();
      }
      //重新评估
      else {
        this.$router.push({ name: 'consult' });
        // this.$router.push({ name: 'extract', params: { photoData: newParams } })
      }
    },
    clearOcrTextInterval(){
      clearInterval(this.timeoutId); // 清除定时器
      clearInterval(this.intervalId1); // 清除定时器
      clearInterval(this.intervalId2); // 清除定时器
    },
    reSubmitOcr() {
      this.respFlag = '0';
      // this.$store.commit('loading/SET_LOADING', true);
      let orcParam = JSON.parse(sessionStorage.getItem("orcParam"))
      if (orcParam) {
        this.params = orcParam;
        // this.imgSrc = 'data:image/jpg;base64,' + this.params.Base64Img;
				this.imgSrc = this.params.Base64Img;
      }
      identifyingApi().then((res) => {
        if (res.data.resultCode == 0) {
          this.identifyingNo = res.data.data;
          let blobToFile = this.base64ImgtoFile(this.imgSrc, "blob");
          let fd = new FormData();
          fd.append("imageFile", blobToFile);
          fd.append("itemsCode", this.params.itemsCode);
          fd.append("identifying", this.identifyingNo);
          fd.append("identifying", this.identifyingNo);
          console.log('identifying', this.identifyingNo);
          fd.append("pictureType", this.params.openFromGallery ? 2 : 1);
          fd.append("healthPropertyIds", JSON.stringify(this.params.selectId));
          console.log('healthPropertyIds', this.params.selectId);
          recognizeApi(fd).then((res) => {
            // this.$store.commit('loading/SET_LOADING', false);
            if (res.data.resultCode == 0) {
              sessionStorage.setItem('taskNo', res.data.data.taskNo);
              this.taskNo = res.data.data.taskNo
              console.log('重新发起this.taskNo',this.taskNo);
              this.getPlanResult = setInterval(() => {
                this.getPlanResultFn();
              }, 2000);
            } else {
              this.$toast(res.data.resultMsg || "失败");
              this.respFlag = '1';
              // this.$store.commit('loading/SET_LOADING', false);
            }
          }).catch((err) => {
            this.respFlag = 1;
            this.displayTextObj = { title: "根据您提供的体检报告，小智正在为您分析核保预测结果，整个分析的过程大概需要1分钟。", p1: "", p2: "", p3: "", p4: "", p5: "" }
            this.clearOcrTextInterval();
            clearInterval(this.getPlanResult);
          });
        }
      }).catch((err) => {
        this.respFlag = 1;
        this.displayTextObj = { title: "根据您提供的体检报告，小智正在为您分析核保预测结果，整个分析的过程大概需要1分钟。", p1: "", p2: "", p3: "", p4: "", p5: "" }
        this.clearOcrTextInterval();
        clearInterval(this.getPlanResult);
      });


    },
    //重新提交--查询进度
    getPlanResultFn() {
      PlanResultApi(this.taskNo).then((res) => {
        this.$store.commit('loading/SET_LOADING', false);
        console.log('res.data.resultCode', res.data.resultCode);
        console.log('res.data.data.tag', res.data.data.tag);
        if (res.data.resultCode == 0) {
          if (res.data.data.tag == 1) {
            // 清除定时器
            clearInterval(this.getPlanResult);
            this.clearOcrTextInterval();
            setTimeout(() => {
              this.$router.push({ name: 'contents' })
              sessionStorage.removeItem("orcParam");
            }, 2000)
          }
        }
        //网络通信不稳定，请重试
        else if (res.data.resultCode == 511) {
          // 重新提交
          this.respFlag = 1;
          this.displayTextObj = { title: "根据您提供的体检报告，小智正在为您分析核保预测结果，整个分析的过程大概需要1分钟。", p1: "", p2: "", p3: "", p4: "", p5: "" }
          this.clearOcrTextInterval();
          clearInterval(this.getPlanResult);
        } else if (res.data.resultCode == 510 || res.data.resultCode == 513) {
          // 重新评估
          this.respFlag = 2;
          this.errorMsg = res.data.resultMsg
          this.displayTextObj = { title: "根据您提供的体检报告，小智正在为您分析核保预测结果，整个分析的过程大概需要1分钟。", p1: "", p2: "", p3: "", p4: "", p5: "" }
          this.clearOcrTextInterval();
          clearInterval(this.getPlanResult);
        }
        else {
          this.clearOcrTextInterval();
          this.respFlag = 3;
          this.$dialog
            .alert({
              message: res.data.resultMsg || "网络繁忙，请稍后重试！",
              getContainer: ".report", // 设置 Dialog 挂载的节点
              confirmButtonText: "确定", // 设置确认按钮的文字
              confirmButtonColor: "#e60012", // 设置确认按钮的文字颜色
            })
            .then(() => {
              clearInterval(this.getPlanResult);
              console.log("点击了确认，弹窗关闭");
              sessionStorage.removeItem("baseData");
              sessionStorage.removeItem("baseContent");
              this.$router.push({ path: "/consult" });
            });
        }
      }).catch((err) => {
        this.respFlag = 1;
        this.displayTextObj = { title: "根据您提供的体检报告，小智正在为您分析核保预测结果，整个分析的过程大概需要1分钟。", p1: "", p2: "", p3: "", p4: "", p5: "" }
        this.clearOcrTextInterval();
        clearInterval(this.getPlanResult);
        // this.respFlag2 = 99;
        // this.$toast(res.data.resultMsg || "失败");
        this.$store.commit('loading/SET_LOADING', false);
      });
    },
    // 遍历文字
    base64ImgtoFile(dataurl, filename) {
      const arr = dataurl.split(',')
      const mime = arr[0].match(/:(.*?);/)[1]
      const suffix = mime.split('/')[1]
      const bstr = atob(arr[1])
      let n = bstr.length
      const u8arr = new Uint8Array(n)
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n)
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime
      })
    },
    async traversalText() {
      for (let key in this.textObj) {
        if (this.respFlag2 !== 0) {
          return;
        }
        await this.tTMethod(this.textObj, key);
      }
    },
    async tTMethod(obj, key) {
      return new Promise((resolve, reject) => {
        let i = 0; // 添加一个变量i用于迭代
        if (key != 'title' && key != 'p1') {
            this.timeoutId = setTimeout(() => {
              this.intervalId2 = setInterval(() => {
              this.displayTextObj[key] += obj[key][i];
              if (i === obj[key].length - 1 || this.respFlag2 !== 0) {
                clearInterval(this.intervalId2); // 清除定时器
                resolve();
              }
              i++;
            }, 200);
          }, 5000); // 五秒后执行
        } else {
            this.intervalId1 = setInterval(() => {
            this.displayTextObj[key] += obj[key][i];
            if (i === obj[key].length - 1 || this.respFlag2 !== 0) {
              clearInterval(this.intervalId1); // 清除定时器
              resolve();
            }
            i++;
          }, 200);
        }
      });
    },
    async gptRequest() {
      this.respFlag1 = await new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(2);
        }, 1000);
      });

      // let res = await scheduleApi()
      // log('res', res)
      console.log(this.respFlag1);
    },
    getrespFlag() {
      this.respFlag = this.respFlag1;
      if (this.respFlag === 3) {
        // 引入 Dialog 组件后，会自动在 Vue 的 prototype 上挂载 $dialog 方法，在所有组件内部都可以直接调用此方法。
        this.$dialog
          .alert({
            message: "系统处理当前任务失败，请稍后重试。",
            getContainer: ".report", // 设置 Dialog 挂载的节点
            confirmButtonText: "确定", // 设置确认按钮的文字
            confirmButtonColor: "#e60012", // 设置确认按钮的文字颜色
          })
          .then(() => {
            console.log("点击了确认，弹窗关闭");
          });
      }
    },
    nowDate() {
      this.timer = dayjs().format("YYYYMMDD");
    },
  },
};
</script>

<style lang="less" scoped>
@dialog-font-size: 15px;
.report {
  margin: 0 10px;
  background-color: #e8f0f3;
  text-align: left;
  font-size: 14px;
  height: 100vh;
}
.header-timer {
  text-align: right;
  margin-top: 2vh;
  margin-right: 4vw;
  font-size: 14px;
  color: #b7bfc1;
}
.header {
  background-color: #ecf1ea;
  color: #c6ba81;
  margin-bottom: 2vh;
  margin-top: 1vh;
  font-size: 14px;
  /* text-indent: 1.1em; */
  padding-right: 5vw;
}
.qr-scanner {
  background-image: linear-gradient(
      0deg,
      transparent 24%,
      rgba(53, 114, 186, 0.1) 25%,
      rgba(53, 114, 186, 0.1) 26%,
      transparent 27%,
      transparent 74%,
      rgba(53, 114, 186, 0.1) 75%,
      rgba(53, 114, 186, 0.1) 76%,
      transparent 77%,
      transparent
    ),
    linear-gradient(
      90deg,
      transparent 24%,
      rgba(53, 114, 186, 0.1) 25%,
      rgba(53, 114, 186, 0.1) 26%,
      transparent 27%,
      transparent 74%,
      rgba(53, 114, 186, 0.1) 75%,
      rgba(53, 114, 186, 0.1) 76%,
      transparent 77%,
      transparent
    );
  background-size: 100% 100%;
  /* background-position: -1rem -1rem; */
  width: 100%;
  height: 34vh;
  position: relative;
  background-image: url("../assets/img/scan_bg.png");
  /* background-color: #3474bd; */
}

.qr-scanner .box {
  width: 75vw;
  height: 28vh;
  max-height: 28vh;
  max-width: 75vh;
  position: relative;
  left: 50%;
  top: 7%;
  transform: translate(-50%, 0%);
  overflow: hidden;
  border: 0.1rem solid rgba(0, 255, 51, 0.2);
}
.box .img {
  position: absolute;
  left: 0;
  top: 0;
  scale: 0.9;
  width: 100%;
  height: 100%;
  object-fit: contain;
}
/* .qr-scanner .angle {
} */

.qr-scanner .line {
  position: absolute;
  z-index: 999;
  height: calc(100% - 2px);
  width: 100%;
  background: linear-gradient(90deg, rgba(0, 255, 51, 0) 43%, #f6f6f6 211%);
  border-right: 3px solid #fff;
  transform: translateY(-100%);
  animation: radar-beam 2s infinite;
  animation-timing-function: cubic-bezier(0.53, 0, 0.43, 0.99);
  animation-delay: 1.4s;
}

.qr-scanner .box:after,
.qr-scanner .box:before,
.qr-scanner .angle:after,
.qr-scanner .angle:before {
  content: "";
  display: block;
  position: absolute;
  width: 10vw;
  height: 10vw;

  border: 0.2rem solid transparent;
}

.qr-scanner .box:after,
.qr-scanner .box:before {
  top: 0;
  border-top-color: #fff;
}

.qr-scanner .angle:after,
.qr-scanner .angle:before {
  bottom: 0;
  border-bottom-color: #fff;
}

.qr-scanner .box:before,
.qr-scanner .angle:before {
  left: 0;
  border-left-color: #fff;
}

.qr-scanner .box:after,
.qr-scanner .angle:after {
  right: 0;
  border-right-color: #fff;
}

@keyframes radar-beam {
  0% {
    transform: translateX(-100%);
  }

  100% {
    transform: translateX(0);
  }
}
.footer {
  background-color: #fff;
  margin-top: 1vh;
  min-height: 32vh;
  // padding: 10px 10px 18px;
}
.footer-item {
  position: relative;
  height: 100%;
  background-color: #fff;
}
.footer-item .robot-icon {
  position: absolute;
  left: -6px;
  top: -12px;
  width: 20px;
  height: 30px;
}
.footer-item .footer-text {
  padding: 5vh 2.5vh 2vh 2vh;
  text-align: left;
  font-size: 14px;
}
.footer-item .footer-text .title,
p {
  font-size: 14px;
  color: #c5c5c5;
  text-indent: 1.1em;
}
.footer-btn {
  width: 62%;
  margin-left: 19%;
  // border-radius: 5px;
  margin-top: 2.8vh;
}
::v-deep .van-nav-bar__title,
::v-deep .van-nav-bar__arrow,
::v-deep .van-nav-bar__left span {
  font-size: 18px !important;
}
</style>
